﻿using Cms.Application.Admin.Views;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;

namespace Cms.Application.Admin.Presenters
{
    public class EditApplicationPresenter : BasePresenter
    {
        private readonly Administrator _administrator;
        private readonly IEditApplicationView _view;

        public EditApplicationPresenter(IEditApplicationView view)
            : this(view, new RepositoryFactory())
        {
        }

        public EditApplicationPresenter(IEditApplicationView view, IRepositoryFactory repositoryFactory)
            : base(view, repositoryFactory)
        {
            _view = view;
            _administrator = AdministratorRepository.GetAdministrator(_view.AdministratorID);
            if (!_administrator.HasPermission.EditApplication)
                _view.RedirectToPermissionDeniedPage();
        }

        public void Initialize()
        {
            if (_view.ApplicationID == -1)
            {
            }
            else
            {
                Domain.Application app = SiteRepository.GetApplication(_view.ApplicationID);
                _view.Name = app.Name;
                _view.Description = app.Description;
            }
        }

        public void Save()
        {
            if (_view.Name.Trim() == "")
                AddValidationError(GetText(_view, "NoNameError"));
            if (!IsValid)
                return;
            Domain.Application app;
            if (_view.ApplicationID == -1)
            {
                app = new Domain.Application { Site = _administrator.CurrentSite };
                app.Site.Applications.Add(app);
            }
            else
            {
                app = SiteRepository.GetApplication(_view.ApplicationID);
            }
            app.Name = _view.Name;
            app.Description = _view.Description;
            SiteRepository.SaveApplication(app);
            _view.SetApplicationID(app.ID);
        }
    }
}